﻿#include"XQPushClientWindow.h"
#include"XQCommandType.h"
#include"XQLoginWidget.h"
#include"XQAlgorithm.h"
#include"XQPushClient.h"
#include"XQHttpClient.h"
#include"XQAppInfo.h"
#include<QMessageBox>
XQPushClientWindow::XQPushClientWindow(QWidget* parent)
	:XQMainWindow(parent,false)
{
	init();
}

void XQPushClientWindow::openWidget(int type)
{
	XQMainWindow::openWidget(type);
}

void XQPushClientWindow::systemSetupWidget()
{
	XQMainWindow::systemSetupWidget();
}

void XQPushClientWindow::userStateChange(userState state)
{
	XQMainWindow::userStateChange(state);
}

void XQPushClientWindow::runCommand(int type)
{
	switch (CommandType(type))
	{
	case CommandType::Login:login();
		break;
	case CommandType::Logout:m_push->http()->close(); appInfo()->userInfo()->setState(userState::Logout);
		break;
	default:
		break;
	}
}

void XQPushClientWindow::login(bool autoLogin)
{
	if (!autoLogin)
	{
		auto login = new XQLoginWidget();
		login->setAttribute(Qt::WA_DeleteOnClose); //# 在关闭时自动删除
		if (windowFlags() & Qt::WindowStaysOnTopHint)
			login->setWindowFlag(Qt::WindowStaysOnTopHint);

		////居中显示
		centerShow(login, this);
		//主窗口禁止编辑
		setEnabled(false);
		//登录窗口关闭后恢复对主窗口的控制
		connect(login, &XQLoginWidget::destroyed, [this] {this->setEnabled(true); });
		//auto url = m_push->http()->url();//服务器地址

		auto acc=m_push->account();
		//当用户编辑账号输入框时，查询头像
		connect(login, &XQLoginWidget::userNameChanged, [=](const QString& userName) {
			acc->Account_portrait(userName);
			if (acc->wait()&&acc->result() == HttpAccount::Result::AccountPortrait)
				login->setPortrait(QPixmap::fromImage(acc->accountData().portrait_data));
			else
				login->setPortrait();
			});
		//登录请求
		connect(login, &XQLoginWidget::login, [=](const QString& account, const QString& password) {
			acc->Account_Login(account,password);
			if (!acc->wait()||acc->error() != HttpAccount::Error::NoError)
			{
				QMessageBox::information(login,"登录账号失败", HttpAccount::error_toChinese(acc->error()));
				return;
			}
			//登录成功
			emit showMessage("开始查询账号信息");
			acc->Account_Info();
			if (acc->wait(10000) && acc->result() == HttpAccount::Result::AccountInfo)
			{
				appInfo()->userInfo()->setAccountData(acc->accountData());
				appInfo()->userInfo()->setState(userState::Login);
				emit showMessage("登录成功");
				login->close();
				//login->deleteLater();
			}
			else
			{
				QMessageBox::information(login, "登录账号信息失败", HttpAccount::error_toChinese(acc->error()));
			}
			
			});
	}
	//////链接登录完成时
	//connect(login, &XQLoginWidget::loginFinish, [=] {login->deleteLater(); });
	//login->setAppInfo(appInfo());

	//if (autoLogin && login->autoLoginState() && appInfo()->mysql()->isOpen())//如果是自动登录的话,在数据库连接上后
	//	login->loginPressed();
}
